<template>
  <div class="box">
    <div class="content person-bg">
      <Selecurency
        :listparam="{ currency_recharge_status: true }"
        :currencyId="currencyId"
        @chainlist="getcurencychain"
        @getCurrency="getCurrency"
        @getMinimum="getMinimum"
        @getCurrencyval="getCurrencyAccuracy"
      />
      <div class="recharge-info">
        <div class="textperson-t3 text-14 text-left mb-12">
          {{ $t("assets.mainnetName") }}
        </div>
        <div class="radio-box flex js-sp text-14 mb-30">
          <div
            class="radio over-bg radius flex js-st align-center"
            v-for="(item, index) in state.urlList"
            :key="index"
            :class="{ 'bd-3D': state.label === index }"
          >
            <el-radio v-model="state.label" :label="index" @change="changeLink">
              <span
                class="name"
                :class="{ 'text-bold text-login': state.label === index }"
              >
                {{ item.chain_protocol.code }}
              </span>
            </el-radio>
          </div>
        </div>
        <div
          class="qrcode over-bg"
          v-loading="state.loading"
          ref="qrCodeUrl"
        ></div>
      </div>

      <div class="qrcode-link over-bg flex js-sp align-center text-14">
        <div class="text-bold textperson-t1 flex-shrink-0">
          {{ $t("assets.rechargeAddress") }}
        </div>
        <div
          class="link-center text-left text-bold textperson-t2 flex-grow-1 mg-lf-base"
        >
          {{ state.rechargeurl }}
        </div>
        <div
          class="personlink point flex-shrink-0 mg-lf-base"
          @click="copy(state.rechargeurl)"
        >
          {{ $t("global.copy") }}
        </div>
      </div>

      <div class="recharge-info">
        <div v-if="!wallet_status && recharge_manual" class="mg-tp-md">
          <el-form ref="ruleForm" :model="rechargeForm" class="demo-ruleForm">
            <el-form-item
              v-if="recharge_manual_hash"
              :label="$t('recharge.hashAddress')"
              prop="recharge_hash"
            >
              <el-input
                v-model="rechargeForm.recharge_hash"
                :placeholder="$t('recharge.hashAddressTip')"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="recharge_manual_amount"
              :label="$t('recharge.transferAmount')"
              prop="recharge_amount"
            >
              <el-input
                v-model="rechargeForm.recharge_amount"
                @input="(val) => changeAmount(val)"
                :placeholder="$t('recharge.amountTip')"
              ></el-input>
            </el-form-item>
            <div v-if="recharge_manual_transaction" class="mg-tp-xl text-left">
              <div class="lable mg-bt-xs">
                {{ $t("legal.transferScreenshot") }}
              </div>
              <el-upload
                accept
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handlePicture"
                :before-upload="beforeUpload"
              >
                <div
                  v-if="rechargeForm.transaction_image_url"
                  class="upload-box"
                >
                  <img
                    class="shoot-img"
                    :src="rechargeForm.transaction_image_url"
                    alt=""
                  />
                </div>
                <div v-else class="upload-box flex js-ct">
                  <i class="el-icon-plus text-30"></i>
                </div>
              </el-upload>
            </div>
            <div class="mg-tp-xl mb-20">
              <el-button
                style="width:100%;height:46px"
                @click="handleSubmit"
                class="login-btn share-color"
                :disabled="state.loading"
                >{{ $t("feedback.submit") }}</el-button
              >
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <div class="tip-box bdt-borderBase mb-20 person-bg">
      <div class="tip over-bg radius flex js-sp align-center">
        <div class="tip-left textperson-t1 text-20 flex align-center js-ct">
          <div>{{ $t("tips.tips") }}</div>
        </div>
        <ul class="tip-right text-12 textperson-t3 text-left">
          <li>• {{ $t("tips.tip1", { currency: state.currency }) }}</li>
          <li>• {{ $t("tips.tip2", { currency: "USDT" }) }}</li>
          <!-- <li>
            •
            {{
              $t("tips.tip3", {
                minimum: state.minimum,
                currency: state.currency,
              })
            }}
          </li> -->
          <li>
            •
            {{ $t("tips.tip4") }}
          </li>
          <li>• {{ $t("tips.tip5") }}</li>
        </ul>
      </div>
    </div>
    <div class="recharge-record person-bg">
      <div class="textperson-t3 text-left text-14 flex js-sp mb-8">
        {{ $t("assets.rechargeRecord") }}
        <router-link to="/person/AssetsRecord?active=1" class="personlink">{{
          $t("assets.allRecords")
        }}</router-link>
      </div>

      <div>
        <Record />
      </div>
    </div>
  </div>
</template>
<script>
import { reactive, onMounted, ref } from "vue";
import Selecurency from "./selectcurency.vue";
import Record from "./record-recharge.vue";
import { userChainAddressList } from "@/api/assets";
import { Copy, decimalDigitsInputFilter, toBeNumber } from "@/utils/common.js";
import QRcode from "qrcodejs2";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { RechargeManual,charge_currency_list} from "@/api/assets";
import UseSystemSetting from "@/commonapi/useSystemSetting";

export default {
  name: "RechargeBox",
  components: { Selecurency, Record },
  props: { currencyId: Number },
  setup() {
    const { t } = useI18n();
    const state = reactive({
      tableData: [],
      urlList: [],
      label: 0,
      rechargeurl: "",
      loading: false,
      currency: "",
      minimum: 0,
      number_accuracy: 0,
    });
    /**
     * methods
     */
    onMounted(() => {});
    const changeLink = (val) => {
      state.rechargeurl = state.urlList[val].in_address;
      creatQrCode(state.urlList[val].in_address);
    };
    const qrCodeUrl = ref();
    const creatQrCode = (url) => {
      state.loading = true;
      qrCodeUrl.value.innerHTML = "";
      // eslint-disable-next-line no-unused-vars
      var qrcode = new QRcode(qrCodeUrl.value, {
        text: url, // 需要转换为二维码的内容
        width: 120,
        height: 120,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRcode.CorrectLevel.H,
      });
      state.loading = false;
    };
    const changeAmount = (val) => {
      console.log(val);
      let tempVal = toBeNumber(val);
      rechargeForm.recharge_amount = decimalDigitsInputFilter(
        tempVal,
        state.number_accuracy
      );
    };
    // 获取充值地址
    const getrechargeUrl = (id) => {
      userChainAddressList(id).then((res) => {
        let list = [];
        list = res.data.currency_protocols;
        state.rechargeurl = list[0].in_address;
        creatQrCode(list[0].in_address);
        state.urlList = list;
        state.label = 0;
      });
    };
    const getcurencychain = (val, id) => {
      console.log('获取地在？')
      getrechargeUrl(id);
      rechargeForm.currency_id = id;
    };
    const getCurrencyAccuracy = (val) => {
      state.number_accuracy = val.number_accuracy;
    };
    const getCurrency = (val) => {
      console.log(val);
      state.currency = val;
    };
    const getMinimum = (val) => {
      console.log(val);
      state.minimum = val;
    };
    const copy = (val) => {
      Copy(val).then(() => {
        ElMessage({
          type: "success",
          message: "ok",
        });
      });
    };
    // 提交表单
    const rechargeForm = reactive({
      currency_chain_name: "",
      currency_id: null,
      recharge_amount: null,
      recharge_hash: "",
      transaction_image_url: "",
    });
    // 获取开关状态
    const {
      wallet_status,
      recharge_manual,
      recharge_manual_amount,
      recharge_manual_hash,
      recharge_manual_transaction,
    } = UseSystemSetting();
    // 转账截图
    const uploadUrl = window.VUE_APP_API + "/file/upload";
    const handlePicture = (res) => {
      rechargeForm.transaction_image_url = res.data.source_url;
    };
    const beforeUpload = (file) => {
      let index = file.type.lastIndexOf("/");
      //获取后缀
      let ext = file.type.substr(index + 1);
      if (!isAssetTypeAnImage(ext)) {
        return false;
      }
    };
    // 判断是否是图片
    const isAssetTypeAnImage = (ext) => {
      return (
        [
          "png",
          "jpg",
          "jpeg",
          "bmp",
          "gif",
          "webp",
          "psd",
          "svg",
          "tiff",
        ].indexOf(ext.toLowerCase()) !== -1
      );
    };
    // 提交
    const handleSubmit = () => {
      rechargeForm.currency_chain_name =
        state.urlList[state.label].user_chain_name;
      if (!rechargeForm.recharge_hash && recharge_manual_hash.value) {
        ElMessage({
          type: "warning",
          message: t("recharge.hashAddressTip"),
        });
        return;
      }
      if (!rechargeForm.recharge_amount && recharge_manual_amount.value) {
        ElMessage({
          type: "warning",
          message: t("recharge.amountTip"),
        });
        return;
      }
      if (
        state.minimum > rechargeForm.recharge_amount &&
        recharge_manual_amount.value
      ) {
        ElMessage({
          type: "warning",
          message: t("recharge.minTip", { num: state.minimum }),
        });
        return;
      }
      if (
        !rechargeForm.transaction_image_url &&
        recharge_manual_transaction.value
      ) {
        ElMessage({
          type: "warning",
          message: t("recharge.cutShootUploadTip"),
        });
        return;
      }
      rechargeForm.recharge_amount = parseFloat(rechargeForm.recharge_amount);
      state.loading = true;
      RechargeManual(rechargeForm)
        .then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: "success",
              message: t("recharge.waitCheckTip"),
            });
            rechargeForm.recharge_hash = null;
            rechargeForm.transaction_image_url = "";
            rechargeForm.recharge_amount = null;
          }
        })
        .finally(() => {
          state.loading = false;
        });
    };
    return {
      state,
      getrechargeUrl,
      changeLink,
      creatQrCode,
      qrCodeUrl,
      copy,
      getcurencychain,
      getCurrency,
      getMinimum,
      handleSubmit,
      rechargeForm,
      wallet_status,
      recharge_manual,
      recharge_manual_amount,
      recharge_manual_hash,
      recharge_manual_transaction,
      uploadUrl,
      handlePicture,
      beforeUpload,
      changeAmount,
      decimalDigitsInputFilter,
      getCurrencyAccuracy,
      toBeNumber,
    };
  },
};
</script>

<style scoped lang="less">
.content {
  padding: 9px 12px 30px;
  box-sizing: border-box;
}
.recharge-info {
  width: 472px;
  margin: 0 auto;
}
.is-rtl .recharge-info:deep(.el-form-item__label) {
  float: right;
}
.mb-12 {
  margin-bottom: 12px;
}
.mb-8 {
  margin-bottom: 8px;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-24 {
  margin-bottom: 24px;
}
.mb-20 {
  margin-bottom: 20px;
}
.radio-box {
  width: 100%;
  height: 42px;
}
.radio {
  width: 222px;
  height: 100%;
  padding: 0 15px;
}
.name {
  margin-inline-start: 58px;
  margin-inline-end: 50px;
}
.bd-3D {
  border: 1px solid @blue;
}
.qrcode {
  width: 120px;
  height: 120px;
  margin: 0 auto 24px;
  img {
    width: 100%;
    height: 100%;
  }
}
.qrcode-link {
  width: fit-content;
  min-width: 472px;
  max-width: 100%;
  margin: 0 auto;
  height: 34px;
  border-radius: 36px;
  padding: 0 21px;
  box-sizing: border-box;
}
.link-center {
  min-width: 300px;
  overflow: hidden;
}
.tip-box {
  width: 100%;
  height: 132px;
  padding: 12px;
  box-sizing: border-box;
}
.tip {
  width: 100%;
  height: 100%;
}
.tip-left {
  width: 128px;
  height: 100%;
  // line-height: 108px;
}
.tip-right {
  width: 800px;
  line-height: 16.8px;
}
.recharge-record {
  width: 100%;
  padding: 30px 20px;
  box-sizing: border-box;
}
.upload-box {
  width: 100px;
  height: 100px;
  background: #f8f8f8;
  color: #ffffff;
  i {
    line-height: 100px;
  }
  .shoot-img {
    width: 100%;
    height: 100%;
  }
}
.lable {
  color: #606266;
}
</style>
